﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI.HtmlControls;

namespace Beetle.Web.UI.WebControls
{
    [Themeable(true)]
    public class ToolBarButton : System.Web.UI.WebControls.CompositeControl, IButtonControl, IPostBackEventHandler
    {
        // Fields
        private static readonly object EventClick = new object();
        private static readonly object EventCommand = new object();

        // Events
        [Category("Action"), Description("Button_OnClick")]
        public event EventHandler Click
        {
            add
            {
                base.Events.AddHandler(EventClick, value);
            }
            remove
            {
                base.Events.RemoveHandler(EventClick, value);
            }
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }

        [Category("Action"), Description("Button_OnCommand")]
        public event CommandEventHandler Command
        {
            add
            {
                base.Events.AddHandler(EventCommand, value);
            }
            remove
            {
                base.Events.RemoveHandler(EventCommand, value);
            }
        }

        [NotifyParentProperty(true)]
        [DefaultValue("")]
        [Editor(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(UITypeEditor))]
        [Localizable(true)]
        public string ImageUrl
        {
            get
            {
                string url = (string)this.ViewState["ImageUrl"];
                return url == null ? String.Empty : url;
            }

            set { ViewState["ImageUrl"] = value; }
        }

        [NotifyParentProperty(true)]
        [DefaultValue("")]
        [Editor(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(UITypeEditor))]
        [Localizable(true)]
        public string DisabledImageUrl
        {
            get
            {
                string url = (string)this.ViewState["DisImageUrl"];
                if (url == null)
                {
                    if (this.DesignMode)
                    {
                        return string.Empty;
                    }

                    if (!string.IsNullOrEmpty(this.ImageUrl) && this.ImageUrl.LastIndexOf('.') != -1)
                    {
                        string disImageUrl = this.ImageUrl.Insert(this.ImageUrl.LastIndexOf('.'), "_dis");
                        return disImageUrl;
                    }
                }

                return url;
            }

            set { ViewState["DisImageUrl"] = value; }
        }

        /// <summary>
        ///  
        /// </summary>
        [Category("Behavior")]
        [Description(" ")]
        [Browsable(true)]
        [NotifyParentProperty(true)]
        [CssClassProperty]
        public string HoverCssClass
        {
            get
            {
                object o = ViewState["HoverCssClass"];

                if (o == null)
                {
                    if (this.DesignMode)
                    {
                        return string.Empty;
                    }

                    if (!string.IsNullOrEmpty(this.CssClass))
                    {
                        string disImageUrl = this.CssClass + "_hover";
                        return disImageUrl;
                    }
                }

                return (string)o;
            }

            set
            {
                ViewState["HoverCssClass"] = value;
            }
        }

        /// <summary>
        /// 是否自动回调
        /// </summary>
        [Category("Behavior")]
        [Description("是否自动回调")]
        [Browsable(true)]
        [NotifyParentProperty(true)]
        [DefaultValue(true)]
        public bool AutoPostBack
        {
            get
            {
                object o = ViewState["AutoPostBack"];
                return o != null ? (bool)o : true;
            }

            set
            {
                ViewState["AutoPostBack"] = value;
            }
        }



        // Methods
        public ToolBarButton()
        {
            this.Style.Add("float", "left");
            this.Style.Add("line-height", "normal");
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            if (this.Page != null)
            {
                this.Page.VerifyRenderingInServerForm(this);
            }

            bool isEnabled = base.IsEnabled;

            if (this.Enabled && isEnabled && !string.IsNullOrEmpty(this.CssClass) && !string.IsNullOrEmpty(this.HoverCssClass))
            {
                base.Attributes.Remove("onmouseover");
                base.Attributes.Remove("onmouseout");

                writer.AddAttribute("onmouseover", "this.className='" + this.HoverCssClass + "';");
                writer.AddAttribute("onmouseout", "this.className='" + this.CssClass + "';");
            }

            PostBackOptions postBackOptions = this.GetPostBackOptions();

            string firstScript = string.Empty;
            if (isEnabled)
            {
                firstScript = this.EnsureEndWithSemiColon(this.OnClientClick);
                if (base.HasAttributes)
                {
                    string str3 = base.Attributes["onclick"];
                    if (str3 != null)
                    {
                        firstScript = firstScript + this.EnsureEndWithSemiColon(str3);
                        base.Attributes.Remove("onclick");
                    }
                }

                if (this.Page != null && this.AutoPostBack)
                {
                    string postBackEventReference = this.Page.ClientScript.GetPostBackEventReference(postBackOptions, false);
                    if (postBackEventReference != null)
                    {
                        firstScript = this.MergeScript(firstScript, postBackEventReference);
                    }
                }
            }

            if (this.Page != null)
            {
                this.Page.ClientScript.RegisterForEventValidation(postBackOptions);
            }

            if (firstScript.Length > 0)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Onclick, firstScript);
            }

            if (this.Enabled && !isEnabled)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
            }
            else
            {
                this.Style.Add(HtmlTextWriterStyle.Cursor, "pointer");
            }

            base.AddAttributesToRender(writer);
        }

        private string MergeScript(string firstScript, string secondScript)
        {
            if (!string.IsNullOrEmpty(firstScript))
            {
                return (firstScript + secondScript);
            }

            if (secondScript.TrimStart(new char[0]).StartsWith("javascript:", StringComparison.Ordinal))
            {
                return secondScript;
            }

            return ("javascript:" + secondScript);
        }

        private string EnsureEndWithSemiColon(string value)
        {
            if (value != null)
            {
                int length = value.Length;
                if ((length > 0) && (value[length - 1] != ';'))
                {
                    return (value + ";");
                }
            }

            return value;
        }

        protected virtual PostBackOptions GetPostBackOptions()
        {
            PostBackOptions options = new PostBackOptions(this, string.Empty);
            options.ClientSubmit = false;
            if (this.Page != null)
            {
                if (this.CausesValidation && (this.Page.GetValidators(this.ValidationGroup).Count > 0))
                {
                    options.PerformValidation = true;
                    options.ValidationGroup = this.ValidationGroup;
                }
                if (!string.IsNullOrEmpty(this.PostBackUrl))
                {
                    options.ActionUrl = HttpUtility.UrlPathEncode(base.ResolveClientUrl(this.PostBackUrl));
                }

                options.ClientSubmit = true;
            }
            return options;
        }

        protected virtual void OnClick(EventArgs e)
        {
            EventHandler handler = (EventHandler)base.Events[EventClick];
            if (handler != null)
            {
                handler(this, e);
            }
        }

        protected virtual void OnCommand(CommandEventArgs e)
        {
            CommandEventHandler handler = (CommandEventHandler)base.Events[EventCommand];
            if (handler != null)
            {
                handler(this, e);
            }

            base.RaiseBubbleEvent(this, e);
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            this.ChildControlsCreated = true;
            this.Controls.Clear();

            HtmlTable mainTable = new HtmlTable();
            mainTable.Border = 0;
            mainTable.CellPadding = 0;
            mainTable.CellSpacing = 4;
            mainTable.Rows.Add(new HtmlTableRow());
            mainTable.Rows[0].Cells.Add(new HtmlTableCell());
            mainTable.Rows[0].Cells.Add(new HtmlTableCell());

            mainTable.Rows[0].Cells[0].Align = "center";
            mainTable.Rows[0].Cells[0].VAlign = "middle";

            mainTable.Rows[0].Cells[1].Align = "center";
            mainTable.Rows[0].Cells[1].VAlign = "middle";

            if (this.Enabled && base.Enabled)
            {
                if (!string.IsNullOrEmpty(this.ImageUrl))
                {
                    Image image = new Image();
                    image.ID = "imgToolBar";
                    image.ImageUrl = this.ImageUrl;

                    mainTable.Rows[0].Cells[0].Controls.Add(image);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(this.DisabledImageUrl))
                {
                    Image image = new Image();
                    image.ID = "imgToolBar";
                    image.ImageUrl = this.DisabledImageUrl;

                    mainTable.Rows[0].Cells[0].Controls.Add(image);
                }
            }

            mainTable.Rows[0].Cells[1].Controls.Add(new LiteralControl("<nobr>" + this.Text + "</nobr>"));

            this.Controls.Add(mainTable);
        }

        protected virtual void RaisePostBackEvent(string eventArgument)
        {
            if (this.CausesValidation)
            {
                this.Page.Validate(this.ValidationGroup);
            }

            this.OnClick(EventArgs.Empty);
            this.OnCommand(new CommandEventArgs(this.CommandName, this.CommandArgument));
        }


        void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
        {
            this.RaisePostBackEvent(eventArgument);
        }

        // Properties
        [Description("Button_CausesValidation"), Category("Behavior"), DefaultValue(true), Themeable(false)]
        public virtual bool CausesValidation
        {
            get
            {
                object obj2 = this.ViewState["CausesValidation"];
                if (obj2 != null)
                {
                    return (bool)obj2;
                }
                return true;
            }
            set
            {
                this.ViewState["CausesValidation"] = value;
            }
        }

        [Bindable(true), DefaultValue(""), Themeable(false), Category("Behavior"), Description("WebControl_CommandArgument")]
        public string CommandArgument
        {
            get
            {
                string str = (string)this.ViewState["CommandArgument"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["CommandArgument"] = value;
            }
        }

        [Themeable(false), Category("Behavior"), Description("WebControl_CommandName"), DefaultValue("")]
        public string CommandName
        {
            get
            {
                string str = (string)this.ViewState["CommandName"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["CommandName"] = value;
            }
        }

        [Themeable(false), Description("Button_OnClientClick"), DefaultValue(""), Category("Behavior")]
        public virtual string OnClientClick
        {
            get
            {
                string str = (string)this.ViewState["OnClientClick"];
                if (str == null)
                {
                    return string.Empty;
                }
                return str;
            }
            set
            {
                this.ViewState["OnClientClick"] = value;
            }
        }

        [DefaultValue(""), Category("Behavior"), Description("Button_PostBackUrl"), Editor("System.Web.UI.Design.UrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor)), Themeable(false), UrlProperty("*.aspx")]
        public virtual string PostBackUrl
        {
            get
            {
                string str = (string)this.ViewState["PostBackUrl"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["PostBackUrl"] = value;
            }
        }

        [Description("Button_Text"), Category("Appearance"), DefaultValue(""), Localizable(true), Bindable(true)]
        public string Text
        {
            get
            {
                string str = (string)this.ViewState["Text"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["Text"] = value;
            }
        }



        [Description("PostBackControl_ValidationGroup"), Category("Behavior"), DefaultValue(""), Themeable(false)]
        public virtual string ValidationGroup
        {
            get
            {
                string str = (string)this.ViewState["ValidationGroup"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["ValidationGroup"] = value;
            }
        }
    }
}
